import Message from "../../../miniprogram_npm/tdesign-miniprogram/message/index";
import { CardCategory, CardCategoryList, EnergyType, TriggerType, TriggerTypeList, TriggerTypeMap, UaCard } from "../../../models/ua-card.model";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { UaUserDeckDto, UaUserDeckEntity } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaCardService } from "../../../services/ua-card.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";


// pages/user/user-deck-add/user-deck-add.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    CND_HOST: GlobalService.FILE_HOST,
    idCountMap: {} as { [key: number]: number },
    characterList: [] as UaCard[],
    eventList: [] as UaCard[],
    fieldList: [] as UaCard[],
    showWarnConfirm: false,
    deckName: "",
    logo: "",
    energyCountMap: {} as { [key: string]: number },
    energyTypeKeys: [] as string[],
    energeColorMap: {} as { [key: string]: string },
    categoryCountMap: {} as { [key: string]: number },
    categoryTypeKeys: [] as string[],
    triggerCountMap: {} as { [key: string]: number },
    triggerTypeKeys: [] as string[],
    total: 0,
    totalTrigger: 0,
    published: false,
    ranked: false,
    description: '比赛名称：\n比赛人数： 人\n卡组名次：\n卡组思路：\n',
    tagText: '默认分组',
    tagList: [{ label: "默认分组", value: '' }],
    tagVisible: false,
    tag: '',
    detailVisible: false,
    detailCard: {} as UaCard,
    max: 0,
    coverCardList: [] as string[],
    deckCardImgList: [] as string[]
  },

  customData: {
    ipId: undefined as number | undefined,
    deckId: undefined as number | undefined,
    authorId: undefined as number | undefined,
    idCountMap: {} as { [key: number]: number },
    cardDeckNoCountMap: {} as { [key: string]: number },
    energyCountOrderMap: {} as { [key: string]: number },
    cardList: [] as UaCard[],
    colorCount: 0,
    finalCount: 0,
    specialCount: 0,
    c0: 0,
    c1: 0,
    energyTypeCountMap: {} as { [key: string]: number },
    fromSearch: false,
    mainEnergyType: undefined as EnergyType | undefined,
    duplicate: false,
    submiting: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    GlobalService.clearCurrentEditingDeckInfo();
    this.customData.ipId = options.ipId;
    this.customData.duplicate = !!options.duplicate;
    if (options.deckId) {
      this.customData.deckId = options.deckId;
      wx.setNavigationBarTitle({
        title: '编辑卡组'
      });
    } else {
      wx.setNavigationBarTitle({
        title: '创建卡组'
      });
    }
    UaCardService.findListByIpId(options.ipId).then((response: UaCard[]) => {
      this.customData.cardList = response;
      if (this.customData.deckId) {
        this.initDeck();
      }
    });
    UaIpService.fetchUaIp(options.ipId).then((response: UaIpEntity) => {
      if (response) {
        this.setData({
          logo: response.ipTitleLogo
        });
      }
    });
    this.initTags();
    const categoryCountMap: { [key: string]: number } = {};
    const categoryTypeKeys: string[] = [];
    for (const item of CardCategoryList) {
      categoryTypeKeys.push(item.value.toString().toLowerCase());
      categoryCountMap[item.value.toString().toLowerCase()] = 0;
    }
    const triggerCountMap: { [key: string]: number } = {};
    const triggerTypeKeys: string[] = [];
    for (const item of TriggerTypeList) {
      triggerTypeKeys.push(item.value.toString().toLowerCase());
      triggerCountMap[item.value.toString().toLowerCase()] = 0;
    }

    this.setData({
      categoryTypeKeys,
      categoryCountMap,
      triggerTypeKeys,
      triggerCountMap
    })
  },

  initTags() {
    UserDeckService.getTags().then((response: string[]) => {
      if (response) {
        const tagList = [{ label: "默认分组", value: '' }];
        for (const tag of response) {
          tagList.push({
            label: tag, value: tag
          })
        }
        tagList.push({
          label: "+新增分组",
          value: "+新增分组"
        });
        this.setData({ tagList });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.enableAlertBeforeUnload({
      message: "卡组未保存，真的要返回吗？",
    })
    if (this.customData.fromSearch) {
      this.customData.idCountMap = JSON.parse(JSON.stringify(GlobalService.ID_COUNT_MAP));
      this.customData.cardDeckNoCountMap = JSON.parse(JSON.stringify(GlobalService.DECKNO_COUNT_MAP));
      this.customData.fromSearch = false;
      this.refreshInfo();
    }
  },

  initDeck() {
    UserDeckService.findById(this.customData.deckId!).then((response: UaUserDeckDto) => {
      if (response) {
        this.customData.mainEnergyType = response.mainEnergyType;
        this.customData.authorId = response.userId;
        if (this.customData.duplicate) {
          this.customData.authorId = undefined;
        }
        const cardMap: { [key: number]: UaCard } = {}
        this.customData.cardList.map((card: UaCard) => {
          cardMap[card.id!] = card;
        });
        const idCountMap: { [key: number]: number } = {};
        const cardDeckNoCountMap: { [key: string]: number } = {};
        for (const item of response.cardList ?? []) {
          idCountMap[item.id!] = item.count!;
          const card = cardMap[item.id!];
          if (card) {
            if (!cardDeckNoCountMap[card.cardDeckNo!]) {
              cardDeckNoCountMap[card.cardDeckNo!] = 0;
            }
            cardDeckNoCountMap[card.cardDeckNo!] += item.count!;
          }
        }
        this.customData.idCountMap = idCountMap;
        this.customData.cardDeckNoCountMap = cardDeckNoCountMap;
        let coverCardList: string[] = []
        if (!!response.cover) {
          coverCardList = response.cover.split(';');
        }
        this.setData({
          deckName: response.name,
          published: response.published,
          description: response.description ? response.description : '比赛名称：\n比赛人数： 人\n卡组名次：\n卡组思路：\n',
          ranked: response.ranked,
          tag: response.tag,
          tagText: response.tag !== "" ? response.tag : '默认分组',
          coverCardList
        })
        this.refreshInfo();
      }
    })
  },

  submit() {

    const cardList: { id: number; count: number }[] = [];
    const ids = Object.keys(this.customData.idCountMap);
    for (const id of ids) {
      if (!this.customData.idCountMap[+id]) {
        continue;
      }
      cardList.push({
        id: +id,
        count: this.customData.idCountMap[+id]
      })
    }
    const keys = Object.keys(this.customData.energyTypeCountMap);
    keys.sort((a, b) => this.customData.energyTypeCountMap[b] - this.customData.energyTypeCountMap[a]);
    const userInfo = LocalStorage.getUserInfo();
    const data: UaUserDeckDto = {
      ipId: this.customData.ipId,
      userId: userInfo?.id,
      name: this.data.deckName,
      published: this.data.published,
      ranked: this.data.ranked,
      description: this.data.ranked ? this.data.description : '',
      mainEnergyType: keys.length > 0 ? (keys[0] as EnergyType) : undefined,
      cardList,
      tag: this.data.tag,
      cover: this.data.coverCardList.length > 0 ? this.data.coverCardList.join(';') : ''
    };
    if (!!this.customData.submiting) {
      return;
    }
    this.customData.submiting = true;
    if (this.customData.deckId && LocalStorage.getUserInfo()?.id === this.customData.authorId) {
      data.id = this.customData.deckId;
    }
    this.confirm(data).then((response: UaUserDeckEntity) => {
      if (response) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `保存成功`,
        });
        setTimeout(() => {
          wx.disableAlertBeforeUnload({
            complete: () => {
              wx.navigateBack();
            }
          });
        }, 1000);
      } else {
        this.customData.submiting = false;
      }
    })
  },

  confirm(data: UaUserDeckDto) {
    if (!!data.id) {
      return UserDeckService.updateDeck(data)
    } else {
      return UserDeckService.createDeck(data)
    }
  },

  refreshInfo() {
    const deckNos: string[] = [];
    const characterList: UaCard[] = [];
    const eventList: UaCard[] = [];
    const fieldList: UaCard[] = [];
    const triggerCountMap: { [key: string]: number } = {};
    const categoryCountMap: { [key: string]: number } = {};
    const energyCountMap: { [key: string]: number } = {};
    const energyTypeCountMap: { [key: string]: number } = {};
    const energyTypeKeys: string[] = [];
    const energeColorMap: { [key: string]: string } = {};
    let total = 0;
    let totalTrigger = 0;
    let c0 = 0;
    let c1 = 0;
    const deckCardImgList: string[] = [];
    for (const card of this.customData.cardList) {
      if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
        deckNos.push(card.cardDeckNo!);
        const c = this.customData.cardDeckNoCountMap[card.cardDeckNo!];
        if (card.triggerType) {
          if (!triggerCountMap[card.triggerType.toString().toLowerCase()]) {
            triggerCountMap[card.triggerType.toString().toLowerCase()] = 0;
          }
          triggerCountMap[card.triggerType.toString().toLowerCase()] += c;
          totalTrigger += c;
        }
      }
      if (!!this.customData.idCountMap[card.id!]) {
        deckCardImgList.push(card.cardImg!.replace('.png', '.jpg'));
        switch (card.cardCategory) {
          case CardCategory.Character:
            characterList.push(card);
            break;
          case CardCategory.Event:
            eventList.push(card);
            break;
          case CardCategory.Field:
            fieldList.push(card);
            break;
        }
        if (card.cardCategory) {
          if (!categoryCountMap[card.cardCategory.toString().toLowerCase()]) {
            categoryCountMap[card.cardCategory.toString().toLowerCase()] = 0;
          }
          categoryCountMap[card.cardCategory.toString().toLowerCase()] += this.customData.idCountMap[card.id!];
          total += this.customData.idCountMap[card.id!];
        }
        const ek = `${card.needEnergyType!.toLowerCase() + card.needEnergyCount!}`;
        energeColorMap[ek] = card.needEnergyType!.toString();
        if (!energyCountMap[ek]) {
          energyCountMap[ek] = 0;
        }
        if (!energyTypeKeys.includes(ek)) {
          energyTypeKeys.push(ek)
          this.customData.energyCountOrderMap[ek] = card.needEnergyCount!;
        }
        energyCountMap[ek] += this.customData.idCountMap[card.id!];
        if (!energyTypeCountMap[card.needEnergyType!]) {
          energyTypeCountMap[card.needEnergyType!] = 0;
        }
        energyTypeCountMap[card.needEnergyType!] += this.customData.idCountMap[card.id!];
        if (card.needEnergyCount === 0) {
          c0 += this.customData.idCountMap[card.id!];
        }
        if (card.needEnergyCount === 1) {
          c1 += this.customData.idCountMap[card.id!];
        }
        this.customData.c0 = c0;
        this.customData.c1 = c1;
      }
    }
    energyTypeKeys.sort((a, b) => this.customData.energyCountOrderMap[a] - this.customData.energyCountOrderMap[b]);
    let max = 0;
    for (const k of energyTypeKeys) {
      max = Math.max(+energyCountMap[k], max);
    }
    this.customData.energyTypeCountMap = energyTypeCountMap;
    this.customData.finalCount = !!triggerCountMap[TriggerType.Final.toLowerCase()] ? triggerCountMap[TriggerType.Final.toLowerCase()] : 0;
    this.customData.colorCount = !!triggerCountMap[TriggerType.Color.toLowerCase()] ? triggerCountMap[TriggerType.Color.toLowerCase()] : 0;
    this.customData.specialCount = !!triggerCountMap[TriggerType.Special.toLowerCase()] ? triggerCountMap[TriggerType.Special.toLowerCase()] : 0;
    const coverCardList = this.data.coverCardList.filter((item) => deckCardImgList.includes(item));
    this.setData({
      characterList,
      eventList,
      fieldList,
      idCountMap: this.customData.idCountMap,
      categoryCountMap,
      triggerCountMap,
      total,
      totalTrigger,
      energyCountMap,
      energyTypeKeys,
      energeColorMap,
      max,
      coverCardList,
      deckCardImgList
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    GlobalService.clearCurrentEditingDeckInfo();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  editName(e: any, needSubmit?: boolean) {
    wx.showModal({
      title: '编辑卡组名称',
      confirmText: "确定",
      cancelText: "取消",
      showCancel: true,
      editable: true,
      placeholderText: "请输入卡组名称",
      content: this.data.deckName,
      success: (res) => {
        if (res.confirm && !!res.content) {
          this.setData({
            deckName: res.content
          });
          if (needSubmit) {
            this.submit()
          }
        }
      }
    });
  },

  search() {
    GlobalService.ID_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.idCountMap));
    GlobalService.DECKNO_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.cardDeckNoCountMap));
    this.customData.fromSearch = true;
    const mainEnergyType = this.customData.mainEnergyType;
    this.customData.mainEnergyType = undefined;
    wx.disableAlertBeforeUnload({
      complete: () => {
        wx.navigateTo({
          url: `/pages/home/ip-card-search/ip-card-search.page?ipId=${this.customData.ipId}${mainEnergyType ? '&mainEnergyType=' + mainEnergyType : ''}`,
        });
      }
    });
  },

  descriptionChange(e: any) {
    console.log(e)
    this.setData({
      description: e.detail.value
    });
  },

  save() {
    let total = 0;
    for (const key in this.data.categoryCountMap) {
      total += this.data.categoryCountMap[key];
    }
    if (total !== 50) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `卡牌总数不是50张`,
      });
      return;
    }
    if (!LocalStorage.getUserInfo()?.nickName) {
      this.editUserInfo({});
      return;
    }
    if (!this.data.deckName) {
      this.editName({}, true);
      return;
    }
    this.submit();
  },

  onIncrease(e: any) {
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    const count = +this.customData.cardDeckNoCountMap[card.cardDeckNo!];
    if (count >= card.limitCount!) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `「${card.cardName}(${card.cardDeckNo})」最多只能投入${card.limitCount}张`,
      });
      return;
    }
    if (!!card.triggerType) {
      let triggerFull = false;
      switch (card.triggerType) {
        case TriggerType.Color:
          triggerFull = this.customData.colorCount >= 4;
          break;
        case TriggerType.Final:
          triggerFull = this.customData.finalCount >= 4;
          break;
        case TriggerType.Special:
          triggerFull = this.customData.specialCount >= 4;
          break;
      }
      if (triggerFull) {
        Message.warning({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `「${TriggerTypeMap[card.triggerType!]}」触发最多只能投入4张`,
        });
        return;
      }
    }
    if (!!card.cardConflict) {
      const conflictList = card.cardConflict.split(',');
      for (const deckNo of conflictList) {
        if (this.customData.cardDeckNoCountMap[deckNo]) {
          Message.warning({
            context: this,
            offset: [20, 32],
            duration: 3000,
            content: `卡组中存在「${deckNo}」，无法投入本卡片。`,
          });
          return;
        }
      }
    }
    this.customData.cardDeckNoCountMap[card.cardDeckNo!]++;
    this.customData.idCountMap[card.id!]++;
    this.refreshInfo();
  },

  onMax(e: any) {
    console.log('max')
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    if (!!card.cardConflict) {
      const conflictList = card.cardConflict.split(',');
      for (const deckNo of conflictList) {
        if (this.customData.cardDeckNoCountMap[deckNo]) {
          return;
        }
      }
    }
    const count = this.customData.cardDeckNoCountMap[card.cardDeckNo!] ? +this.customData.cardDeckNoCountMap[card.cardDeckNo!] : 0;
    let triggerLeft = card.triggerType === TriggerType.Color || card.triggerType === TriggerType.Final || card.triggerType === TriggerType.Special ? 4 : Infinity;
    console.log('triggerLeft')
    if (!!card.triggerType) {
      switch (card.triggerType) {
        case TriggerType.Color:
          triggerLeft -= this.customData.colorCount - count;
          break;
        case TriggerType.Final:
          triggerLeft -= this.customData.finalCount - count;
          break;
        case TriggerType.Special:
          triggerLeft -= this.customData.specialCount - count;
          break;
      }
    }


    let limit = Math.min(triggerLeft, card.limitCount!);
    if (limit > count) {
      this.customData.cardDeckNoCountMap[card.cardDeckNo!] = limit;
      if (!this.customData.idCountMap[card.id!]) {
        this.customData.idCountMap[card.id!] = limit - count;
      } else {
        this.customData.idCountMap[card.id!] += limit - count;
      }
    }

    if (!!card.triggerType) {
      switch (card.triggerType) {
        case TriggerType.Color:
          this.customData.colorCount += limit - count;
          break;
        case TriggerType.Final:
          this.customData.finalCount += limit - count;
          break;
        case TriggerType.Special:
          this.customData.specialCount += limit - count;
          break;
      }
    }
    this.refreshInfo();
  },

  onDecrease(e: any) {
    const id = e.detail;
    const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    if (!card) return;
    if (!this.customData.idCountMap[card.id!]) {
      return;
    }
    const count = +this.customData.idCountMap[card.id!];
    if (count <= 1) {
      wx.showModal({
        title: '是否删除？',
        confirmText: "删除",
        cancelText: "取消",
        showCancel: true,
        confirmColor: "#eb445a",
        success: (res) => {
          if (res.confirm) {
            this.removeCard(card);
          }
        }
      });
      return;
    }
    this.realDecrease(card);
  },

  removeCard(card: UaCard) {
    let arr: UaCard[] = [];
    switch (card.cardCategory) {
      case CardCategory.Character:
        arr = JSON.parse(JSON.stringify(this.data.characterList));
        break;
      case CardCategory.Event:
        arr = JSON.parse(JSON.stringify(this.data.eventList));
        break;
      case CardCategory.Field:
        arr = JSON.parse(JSON.stringify(this.data.fieldList));
        break;
    }
    const index = arr.findIndex((item) => item.id === card.id);
    if (index >= 0) {
      arr.splice(index, 1);
    }
    switch (card.cardCategory) {
      case CardCategory.Character:
        this.setData({
          characterList: arr
        })
        break;
      case CardCategory.Event:
        this.setData({
          eventList: arr
        })
        break;
      case CardCategory.Field:
        this.setData({
          fieldList: arr
        })
        break;
    }
    this.realDecrease(card);
  },

  realDecrease(card: UaCard) {
    this.customData.cardDeckNoCountMap[card.cardDeckNo!]--;
    this.customData.idCountMap[card.id!]--;
    this.refreshInfo();
  },

  publishedChange(e: any) {
    this.setData({
      published: e.detail.value
    })
  },

  rankedChange(e: any) {
    if (e.detail.value) {
      this.setData({
        ranked: e.detail.value,
        published: e.detail.value,
      })
    } else {
      this.setData({
        ranked: e.detail.value
      })
    }
  },


  editUserInfo(e: any) {
    wx.showModal({
      title: '添加卡组前需要先完善个人信息',
      confirmText: "确定",
      cancelText: "取消",
      showCancel: true,
      content: this.data.deckName,
      success: (res) => {
        wx.navigateTo({
          url: '/pages/user/user-info-edit/user-info-edit.page',
        });
      }
    });
  },

  onTagPicker() {
    this.setData({
      tagVisible: true
    });
  },

  onTagPickerCancel() {
    this.setData({
      tagVisible: false
    });
  },

  onTagPickerConfirm(e: any) {
    if (e.detail.value[0] !== "+新增分组") {
      this.setData({
        tagText: e.detail.label[0],
        tag: e.detail.value[0]
      });
    } else {
      wx.showModal({
        title: '新增分组名称',
        confirmText: "确定",
        cancelText: "取消",
        showCancel: true,
        editable: true,
        placeholderText: "请输入新增分组名称",
        success: (res) => {
          if (res.confirm && !!res.content) {
            UserDeckService.addTag(res.content).then(response => {
              if (!!response) {
                this.initTags();
                this.setData({
                  tag: res.content,
                  tagText: res.content
                })
              }
            })
          }
        }
      });
    }
  },

  openDetail(e: any) {
    for (const card of this.customData.cardList) {
      if (card.id === e.detail) {
        this.setData({
          detailVisible: true,
          detailCard: card
        });
        break;
      }
    }
  },

  onDetailVisibleChange(e: any) {
    this.setData({
      detailVisible: e.detail.visible,
    });
  },

  onPrev(e: any) {
    const cardList = [... this.data.characterList, ... this.data.fieldList, ...this.data.eventList];
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < cardList.length; i++) {
      if (detailCardId === cardList[i].id) {
        p = i;
        break;
      }
    }
    if (p === 0) {
      p = cardList.length - 1;
    } else {
      p--;
    }
    this.setData({
      detailCard: cardList[p]
    })
  },

  onNext(e: any) {
    const cardList = [... this.data.characterList, ... this.data.fieldList, ...this.data.eventList];
    const detailCardId = e.detail;
    let p = 0;
    for (let i = 0; i < cardList.length; i++) {
      if (detailCardId === cardList[i].id) {
        p = i;
        break;
      }
    }
    if (p === cardList.length - 1) {
      p = 0;
    } else {
      p++;
    }
    this.setData({
      detailCard: cardList[p]
    })
  },

  clearCover() {
    this.setData({
      coverCardList: []
    })
  },

  selectCover(e: any) {
    const cover = e.currentTarget.dataset["url"];
    let coverList = this.data.coverCardList;
    let index = -1;
    for (let i = 0; i < coverList.length; i++) {
      if (coverList[i] === cover) {
        index = i;
        break;
      }
    }
    if (index === -1) {
      if (coverList.length > 3) {
        return;
      }
      coverList.push(cover);
    } else {
      coverList.splice(index, 1);
    }
    this.setData({
      coverCardList: coverList
    })
  }
})